import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:flutter_color_plugin/flutter_color_plugin.dart';
import 'package:yw_bapp/dao/common_dao.dart';
import 'package:yw_bapp/dao/withdrawal_dao.dart';
import 'package:yw_bapp/model/bind_bank_model.dart';
import 'package:yw_bapp/model/check_bank_model.dart';
import 'package:yw_bapp/pages/my_store.dart';
import 'package:yw_bapp/pages/select_bank_page.dart';
import 'package:yw_bapp/provider/store_info_provider.dart';
import 'package:yw_bapp/utils/check.dart';
import 'package:yw_bapp/utils/precision_limit_formatter.dart';
import 'package:yw_bapp/widgets/custom_route_widget.dart';
import 'package:yw_bapp/widgets/filed_tag_widget.dart';
import 'package:yw_bapp/widgets/m_btn.dart';
import 'package:yw_bapp/widgets/optional_widget.dart';
import 'package:yw_bapp/widgets/safe_area_bar_widget.dart';
import 'package:yw_bapp/widgets/show_toast.dart';

// 兑现账户设置页面
class CashAccountSet extends StatefulWidget {
  @override
  _CashAccountSetState createState() => _CashAccountSetState();
}

class _CashAccountSetState extends State<CashAccountSet> {
  // 下一步按钮的颜色
  bool isActive = false;
  // 按钮点击色
  Color btnActiveColor = ColorUtil.color('#FFC49226');
  // 按钮默认色
  Color btnDefaultColor = ColorUtil.color('#FFCCCCCC');
  // 文字点击色
  Color textActiveColor = Colors.white;
  // 文字默认色
  Color textDefaultColor = Colors.white;
  TextStyle actionStyle =
      TextStyle(color: Colors.black, fontSize: 15, fontWeight: FontWeight.bold);
  String selectName = '去设置';
  // 账户信息
  TextEditingController _accountNameController = TextEditingController();
  String bankName = '';
  String accountName = '';
  String bankAccount = '';
  String subBankName = '';
  bool isEdit = false;
  bool isEnabled;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _accountNameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 请求门店原来的银行账户
    final String oldBankName =
        context.watch<StoreInfoProvider>().storeInfo?.bankName ?? '';
    final String oldAccountName =
        context.watch<StoreInfoProvider>().storeInfo?.accountName ?? '';
    final String oldBankAccount =
        context.watch<StoreInfoProvider>().storeInfo?.bankAccount ?? '';
    final String oldSubBankName =
        context.watch<StoreInfoProvider>().storeInfo?.subBankName ?? '';
    // 赋值
    bankName = bankName == '' ? oldBankName : bankName;
    accountName = accountName == '' ? oldAccountName : accountName;
    bankAccount = bankAccount == '' ? oldBankAccount : bankAccount;
    subBankName = subBankName == '' ? oldSubBankName : subBankName;
    isEnabled = bankAccount == '' ? true : false;
    // isEnabled =true;
    if (accountName == oldAccountName) {
      _accountNameController.text = accountName;
    }
    return Scaffold(
        appBar: XAppBar(
          statusBarColor: ColorUtil.color('#FFC49226'),
          bgColor: ColorUtil.color('#FFC49226'),
          title: "兑现账户设置",
          fun: () {},
        ),
        body: Container(
            color: Color.fromRGBO(233, 233, 233, 1),
            padding: EdgeInsets.only(top: 10),
            child: Column(
              children: [
                // 账户信息
                Container(
                  padding: EdgeInsets.only(left: 15),
                  alignment: Alignment.topLeft,
                  child: Text(
                    "账户信息",
                    style: TextStyle(
                        color: ColorUtil.color("#FF999999"), fontSize: 12),
                  ),
                ),
                Row(
                  children: [
                    Expanded(
                      flex: 1,
                      child: Container(
                        color: Colors.white,
                        margin: EdgeInsets.only(bottom: 10, top: 5),
                        padding: EdgeInsets.only(right: 15, left: 15),
                        child: TextField(
                          controller: _accountNameController,
                          autofocus: false,
                          enabled: isEnabled,
                          decoration: InputDecoration(
                              border: isEnabled
                                  ? UnderlineInputBorder(
                                      borderSide:
                                          BorderSide(color: Colors.grey))
                                  : InputBorder.none,
                              hintText: '$accountName',
                              helperStyle: TextStyle(
                                color: Colors.transparent,
                              ),
                              focusedBorder: UnderlineInputBorder(
                                  borderSide: BorderSide(color: Colors.grey)),
                              hintStyle: TextStyle(
                                  color: ColorUtil.color("#FF999999"),
                                  fontWeight: FontWeight.normal,
                                  fontSize: 13)),
                          style: TextStyle(
                              fontWeight: FontWeight.bold, fontSize: 20),
                          textAlign: TextAlign.left,
                          onChanged: (String value) {
                            setState(() {
                              accountName = value;
                            });
                            canSubmit(context, accountName, bankName,
                                subBankName, bankAccount, isEnabled, isEdit);
                          },
                        ),
                      ),
                    )
                  ],
                ),
                // 兑现账户，银行名字
                Container(
                  margin: EdgeInsets.only(bottom: 10),
                  child: OptionalWidget(
                    leadingText: '兑现账户',
                    callBack: () => {
                      Navigator.of(context)
                          .push(CustomRoute(SelectBankPage(), 5))
                          .then((value) => {
                                if (oldBankAccount == '')
                                  {
                                    setState(() {
                                      bankName = value;
                                    }),
                                    canSubmit(
                                        context,
                                        accountName,
                                        bankName,
                                        subBankName,
                                        bankAccount,
                                        isEnabled,
                                        isEdit)
                                  }
                              })
                    },
                    actionText: "$bankName",
                    actionStyle: bankName != '去设置' ? actionStyle : TextStyle(),
                    iconShow: bankName != '去设置' ? false : true,
                  ),
                ),
                // 支行名字
                Container(
                  margin: EdgeInsets.only(bottom: 10),
                  child: Row(
                    children: [
                      FiledTagWidget(
                        tagName: '银行支行',
                        fieldText: '$subBankName',
                        hintText: '请输入支行名称',
                        typeNum: 2,
                        changeCallback: (String value) {
                          setState(() {
                            subBankName = value;
                          });
                          canSubmit(context, accountName, bankName, value,
                              bankAccount, isEnabled, isEdit);
                        },
                        isEnabled: isEnabled,
                      ),
                    ],
                  ),
                ),
                // 开户行账号
                Row(
                  children: [
                    FiledTagWidget(
                      tagName: '开户行账号',
                      fieldText: ' $bankAccount',
                      hintText: '请输入银行账号',
                      changeCallback: (String value) {
                        print("开户行回调");
                        setState(() {
                          bankAccount = value;
                        });
                        canSubmit(context, accountName, bankName, subBankName,
                            value, isEnabled, isEdit);
                      },
                      isEnabled: isEnabled,
                    ),
                  ],
                ),
                Container(
                  margin: EdgeInsets.only(top: 76),
                  child: MBtn(
                    btnWidth: 325,
                    btnHeight: 47,
                    borderRadius: 5,
                    title: '提交',
                    hasBg: true,
                    textColor: isActive ? textActiveColor : textDefaultColor,
                    bgColor: isActive ? btnActiveColor : btnDefaultColor,
                    borderColor: isActive ? btnActiveColor : btnDefaultColor,
                    function: () {
                      toBindBankAccount(context, accountName, bankName,
                          subBankName, bankAccount, isEnabled);
                    },
                  ),
                )
              ],
            )));
  }

  // 绑定账户
  void toBindBankAccount(BuildContext context, String accountName,
      String bankName, String subBankName, String bankAccount, bool isEnabled) {
    print(' 绑定账户$bankAccount');
    if (!isEnabled) {
      ShowToast.toast(context, msg: "暂不支持编辑", position: ToastPostion.center);
      return;
    }
    // 为空提示
    if (accountName == '' ||
        bankName == '' ||
        bankAccount == ' ' ||
        subBankName == '') {
      ShowToast.toast(context, msg: "请填写完整", position: ToastPostion.center);
    } else {
      // 检查银行账户是否合法
      print('检查银行账户是否合法$bankAccount');
      CommonDao.CheckBank(removeAllSpace(bankAccount)).then((CheckBankModel model) => {
            if (model.stat == 'ok')
              {
                if (model.validated)
      {
      //合法
      WithdrawalDao.BindBankAccount(
              accountName, bankName, subBankName, bankAccount)
          .then((BindBankModel model) => {
                if (model.status == 200)
                  {
                    ShowToast.toast(context,
                        msg: "银行卡绑定成功", position: ToastPostion.center),
                    Navigator.of(context).push(CustomRoute(MyStore(), 5))
                  }
              })
      }
            else
              {
                //不合法
                ShowToast.toast(context,
                        msg: "银行卡账号不合法，请重新输入", position: ToastPostion.center)
              }
          }
      });
    }
  }

  // 提交按钮颜色的变化
  canSubmit(BuildContext context, String accountName, String bankName,
      String subBankName, String bankAccount, bool isEnabled, bool isEdit) {
    setState(() {
      if (isEnabled) {
        //可编辑时
        if (accountName != '' &&
            bankName != '' &&
            bankAccount != '' &&
            subBankName != '') {
          isActive = true;
        } else {
          isActive = false;
        }
      } else {
        // 不可以编辑
        isActive = false;
      }
    });
  }
}
